﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using WorkLogger.Client.DataAccess.Model;

namespace WorkLogger.Client.DataAccess.Repository {
	public class WorkDayRepository : IWorkDayRepository {
		public WorkDay GetWorkDay(DateTime day) {
			using (ISession session = NHibernateHelper.OpenSession()) {
				return session
					.Query<WorkDay>()
					.FirstOrDefault(workDay => workDay.WorkDate == day.Date);
			}
		}

		public void Save(WorkDay workDay) {
			using (ISession session = NHibernateHelper.OpenSession())
			using (ITransaction transaction = session.BeginTransaction()) {
				session.SaveOrUpdate(workDay);
				transaction.Commit();
			}
		}

		public IEnumerable<WorkDay> GetByPeriod(DateTime beginDate, DateTime endDate) {
			using (ISession session = NHibernateHelper.OpenSession()) {
				return session
					.Query<WorkDay>()
					.Where(workDay => workDay.WorkDate >= beginDate)
					.Where(workDay => workDay.WorkDate <= endDate.Date.AddDays(1).AddTicks(-1))
					.ToArray();
			}
		}
	}
}